/**
 * Copyright 2019-2029 geekidea(https://github.com/geekidea)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.plan.commen.entity;

import com.plan.commen.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;

/**
 * @author Zhang
 * @date 2018-11-08
 */
@Slf4j
public abstract class BaseController extends ApiController {


    @Value("${redisDS.group}")
    String redisGroup="";


    @Autowired
    protected UserService userService;

    /**
     * @return 当前用户信息
     */
//    public static UserInfo getUserInfo() {
//        UserInfo adminUser=   (UserInfo)  SecurityUtils.getSubject().getPrincipal();
//        return adminUser;
//    }

    /**
     * @return 当前用户
     */
//    public String getUserInfoAccount(){
//        return getUserInfo().getAccount();
//    }

    /**
     * @return 当前用户id
     */
//    public Long getUserInfoId(){
//        return getUserInfo().getId();
//    }




    /**
     * @param request
     * @return 获取当前微信用户
     */
//    public User getUser (HttpServletRequest request){
//        HttpSession session = request.getSession();
//        User user = (User) session.getAttribute("user");
//         return user = userService.getById(user.getId());
//    }


    /**
     * 获取当前请求
     *
     * @return request
     */
    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
    protected HttpSession getSession() {
        return getRequest().getSession();
    }
    /**
     * 获取当前请求
     *
     * @return response
     */
    protected HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }
    /**
     * 方法名称: renderText<br>
     * 描述：返回普通文本浏览器
     */
    protected void renderText(String text){
        render(text, MediaType.TEXT_HTML_VALUE);
    }

    /**
     * 方法名称: renderJson<br>
     * 描述：返回JSON格式数据
     */
    protected void renderJson(String text){
        render(text,  MediaType.APPLICATION_JSON_UTF8_VALUE );
    }


    /**
     * 获取cookie
     * @param cookieName
     * @return
     */
    protected String getCookie(String cookieName) {
        Cookie[] cookies = getRequest().getCookies();
        for (Cookie cookie : cookies) {
            if (cookieName.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }

        return null;
    }

    /**
     * 设置 cookie
     *
     * @param cookieName
     * @param value
     * @param age
     */
    protected void setCookie(String cookieName, String value, int age) {
        Cookie cookie = new Cookie(cookieName, value);
        cookie.setMaxAge(age);
        getResponse().addCookie(cookie);
    }


    private void render(String text, String contentType){
        HttpServletResponse response;
        try{

            response = getResponse();
            response.setContentType(contentType);

            response.getWriter().write(text);
            response.getWriter().flush();
        }
        catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * 对象转数组
     * @param obj
     * @return
     */
    protected static byte[] objectToByteArray (Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray ();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }

    /**
     * 数组转对象
     * @param bytes
     * @return
     */
    protected static Object byteArrToObject (byte[] bytes) {
        Object object = null;
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);// 创建ByteArrayInputStream对象
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);// 创建ObjectInputStream对象
            object = objectInputStream.readObject();// 从objectInputStream流中读取一个对象
            byteArrayInputStream.close();// 关闭输入流
            objectInputStream.close();// 关闭输入流
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return object;// 返回对象
    }

    /**
     * 群发
     * @return
     */
//    protected void sendMessage(String msg ){
//        Map<String, WebScoketService> map= WebScoketService.webSocketSet;
//        for(String key : map.keySet()) {
//            map.get(key).sendMessage(msg);
//            log.debug("已经向{}发送消息：{}",key,msg);
//
//        }
//
//
//    }

    /**
     * 单发
     * @return
     */
//    protected void sendMessage(String msg,String account ){
//        Map<String,WebScoketService> map= WebScoketService.webSocketSet;
//        for(String key : map.keySet()) {
//            if(key.equals(account)){
//                map.get(key).sendMessage(msg);
//                log.debug("已经向{}发送消息：{}",key,msg);
//                return;
//            }
//        }
//    }

}